/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.client.ui;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.orkut.client.api.samples.greetings.client.GreetingsClientBundle;
import com.google.orkut.client.api.samples.greetings.client.GreetingsCssResource;
import com.google.orkut.client.api.samples.greetings.client.GreetingsMessages;
import com.google.orkut.client.api.samples.greetings.client.selector.Item;
import com.google.orkut.client.api.samples.greetings.client.selector.ItemSelector;
import com.google.orkut.client.api.samples.greetings.client.selector.SearchBox;
import com.google.orkut.client.api.samples.greetings.client.services.UserInfo;

/**
 * A UI widget to select a friend from a list of friends.
 *
 * @author Shishir Birmiwal
 */
public class UserSelector extends ItemSelector<UserInfo> {
  private static final int MAX_USER_NAME_LENGTH = 12;
  public static interface UserSelectedCallback {
    public void userSelected(UserInfo info);
  }

  private UserSelectedCallback cb;
  private final Provider<Item> itemsProvider;
  private final GreetingsCssResource css;

  @Inject
  public UserSelector(
      SearchBox searchBox,
      Provider<Item> itemsProvider,
      GreetingsClientBundle resources,
      GreetingsMessages msgs) {
    super(searchBox);
    this.itemsProvider = itemsProvider;
    this.css = resources.css();
    searchBox.setPromptText(msgs.searchBoxPrompt());
  }

  public void setUserSelectedCallback(UserSelectedCallback cb) {
    this.cb = cb;
  }

  @Override
  protected Item getItemFor(final UserInfo user) {
    Item item = itemsProvider.get();
    item.setStyles(css.userItem(), css.userItemIcon(), css.userItemText());
    item.setText(getClippedString(user.userName, MAX_USER_NAME_LENGTH));
    item.setIcon(user.thumbnailUrl);
    item.setTitle(user.userName);
    item.setSearchKey(user.userName);
    item.setCallback(new Item.ItemSelectedCallback() {
      @Override
      public void selected(Item item) {
        if (cb != null) {
          cb.userSelected(user);
        }
      }
    });
    return item;
  }

  public static String getClippedString(String str, int maxLen) {
    if (str.length() > maxLen) {
      return str.substring(0, maxLen - 1) + "..";
    }
    return str;
  }
}
